package com.haier.uos.weather.collection.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haier.uos.weather.collection.service.IWeatherDataCollectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class WeatherDataCollectionServiceImpl implements IWeatherDataCollectionService {
    private static final long TIME_OUT = 1800L;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String BASE_URI = "http://wthrcdn.etouch.cn/weather_mini";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public void collectionWeatherDataByCityId(String cityId) {
        String uri = BASE_URI + "?citykey=" + cityId;
        ResponseEntity<String> forEntity = restTemplate.getForEntity(uri, String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = null;
        if (forEntity.getStatusCodeValue() == 200) {
            String body = forEntity.getBody();
            try {
                jsonNode = objectMapper.readTree(body);
            } catch (IOException e) {
                logger.error("json转换失败", e);
            }
            if (jsonNode.get("status").asInt() == 1000) {
                stringRedisTemplate.opsForValue().set(uri, body, TIME_OUT, TimeUnit.SECONDS);
            } else {
                logger.info("uri：{} 获取数据失败,失败原因：{}", uri, jsonNode.get("desc").textValue());
            }
        }
    }
}
